<template>
  <a-drawer
    v-model:visible="visible"
    title="流程设计"
    width="98%"
    unmount-on-close
    @cancel="close"
  >
    <bpmn-design ref="bpmnDesignRef" :process-data="currentForm" />

    <template #footer>
      <a-button-group status="normal">
        <a-button :loading="loading" @click.stop="close">
          <template #icon>
            <icon-close />
          </template>
          取消
        </a-button>
        <a-button type="primary" :loading="loading" @click.stop="saveDesign">
          <template #icon>
            <icon-save />
          </template>
          确定
        </a-button>
      </a-button-group>
    </template>
  </a-drawer>
</template>

<script lang="ts" setup>
import { ref, defineEmits, defineExpose, nextTick } from 'vue';
import { deployProcess, FlowProcess } from '@/api/flow/process';
import { cloneDeep } from 'lodash';
import { Message } from '@arco-design/web-vue';
import useLoading from '@/hooks/loading';
import BpmnDesign from '@/components/bpmn-design/index.vue';

const emits = defineEmits(['submit']);

const { loading, setLoading } = useLoading(false);

const visible = ref(false);

const currentForm = ref<FlowProcess>({});

const bpmnDesignRef = ref();

const saveDesign = () => {
  setLoading(true);
  currentForm.value.processData = bpmnDesignRef.value.exportJson();
  deployProcess(currentForm.value).then(() => {
    close();
    emits('submit');
    Message.success('操作成功');
  }).finally(() => {
    setLoading(false);
  });
};

const open = (flowProcess: FlowProcess) => {
  visible.value = true;
  currentForm.value = cloneDeep(flowProcess);
  nextTick(() => {
    bpmnDesignRef.value.setJson(flowProcess.processData);
  });
  setLoading(false);
};

const close = () => {
  visible.value = false;
};

defineExpose({
  open,
  close
});
</script>

<script lang="ts">
export default {
  name: 'DrawerDesign'
};
</script>

<style scoped lang="less">

</style>